/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gps.dao;

import gps.decoder.DecoderHelper;
//import gps.connection.ConnectionManager;
import pe.gps.record.Record;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Date;
import pe.gps.log.Log;

/**
 *
 * @author john
 */
public class VehposDao extends DAO {

//    StatelessSession session;
    private Connection cnx;
    private String q_posdis_co_disgps;
    private String q_posdis_co_imedis;
    private String q_evedis_co_imedis;

    public VehposDao() {
//        cnx = ConnectionManager.getSessionFact();
//        if (cnx != null) {
//            this.estado = true;
//        }
//        ConnectionManager.agregarDao(this);

        q_posdis_co_disgps = "select * from gpsveh.plposdis_co_disgps(p_co_disgps, p_fe_capgps::timestamp with time zone, p_nu_geolat, p_nu_geolon, p_nu_geoalt::smallint,"
                + " p_nu_geodir::smallint, p_nu_geovel::smallint, p_nu_geokmt, p_va_sengps::character, p_va_sengsm::character, p_il_batdis, p_pr_batdis::smallint, p_il_blodis)";

        q_posdis_co_imedis = "select * from gpsveh.plposdis_co_imedis(p_co_imedis, p_fe_capgps::timestamp with time zone, p_nu_geolat, p_nu_geolon, p_nu_geoalt::smallint,"
                + " p_nu_geodir::smallint, p_nu_geovel::smallint, p_nu_geokmt, p_va_sengps::character, p_va_sengsm::character, p_il_batdis, p_pr_batdis::smallint, p_il_blodis)";

        q_evedis_co_imedis = "select * from gpsveh.plevedis_co_imedis(p_co_imedis, p_fe_evegps::timestamp with time zone, p_co_evedis::smallint)";
    }

    public void insVehPos(Record record, int decoder_code) {
        try {
            if (decoder_code == DecoderHelper.VT310) {
                StringBuffer query = new StringBuffer(q_posdis_co_disgps);
                replace(query, "p_co_disgps", record.getId());
                replace(query, "p_fe_capgps", record.getPosicion().getFecha() != null ? "'" + record.getPosicion().getFecha() + "'" : "null");
                replace(query, "p_nu_geolat", record.getPosicion().getLatitud() + "");
                replace(query, "p_nu_geolon", record.getPosicion().getLongitud() + "");
                replace(query, "p_nu_geoalt", record.getPosicion().getAltitud() + "");
                replace(query, "p_nu_geodir", record.getPosicion().getDireccion() + "");
                replace(query, "p_nu_geovel", record.getPosicion().getVelocidad() + "");
                replace(query, "p_nu_geokmt", record.getEstado().getKilometraje() + "");
                replace(query, "p_va_sengps", record.getEstado().getSenal_gps() != null ? "'" + record.getEstado().getSenal_gps() + "'" : "null");
                replace(query, "p_va_sengsm", record.getEstado().getSenal_gsm() != null ? "'" + record.getEstado().getSenal_gsm() + "'" : "null");
                replace(query, "p_il_batdis", record.getEstado().getBatdis() + "");
                replace(query, "p_pr_batdis", record.getEstado().getCarga_bateria() + "");
                replace(query, "p_il_blodis", record.getEstado().getBloqueado() + "");
                execute(query.toString(), decoder_code);
            } else {
                StringBuffer query = new StringBuffer(q_posdis_co_imedis);
                replace(query, "p_co_imedis", record.getId() != null ? "'" + record.getId() + "'" : "null");
                replace(query, "p_fe_capgps", record.getPosicion().getFecha() != null ? "'" + record.getPosicion().getFecha() + "'" : "null");
                replace(query, "p_nu_geolat", record.getPosicion().getLatitud() + "");
                replace(query, "p_nu_geolon", record.getPosicion().getLongitud() + "");
                replace(query, "p_nu_geoalt", record.getPosicion().getAltitud() + "");
                replace(query, "p_nu_geodir", record.getPosicion().getDireccion() + "");
                replace(query, "p_nu_geovel", record.getPosicion().getVelocidad() + "");
                replace(query, "p_nu_geokmt", record.getEstado().getKilometraje() + "");
                replace(query, "p_va_sengps", record.getEstado().getSenal_gps() != null ? "'" + record.getEstado().getSenal_gps() + "'" : "null");
                replace(query, "p_va_sengsm", record.getEstado().getSenal_gsm() != null ? "'" + record.getEstado().getSenal_gsm() + "'" : "null");
                replace(query, "p_il_batdis", record.getEstado().getBatdis() + "");
                replace(query, "p_pr_batdis", record.getEstado().getCarga_bateria() + "");
                replace(query, "p_il_blodis", record.getEstado().getBloqueado() + "");
                execute(query.toString(), decoder_code);
            }
        } catch (Exception e) {
            Log.log("[VehposDao][" + DecoderHelper.getDecoderName(decoder_code) + "]Error: " + e, Log.ERROR);
        }
    }

    public void insAlarma(Record record) {
        String query = q_evedis_co_imedis
                .replace("p_co_imedis", record.getId() != null ? "'" + record.getId() + "'" : null)
                .replace("p_fe_evegps", record.getPosicion().getFecha() != null ? "'" + record.getPosicion().getFecha() + "'" : "null")
                .replace("p_co_evedis", record.getAlarma().getAlarma() + "");
        execute(query, null);
    }

    private ResultSet execute(String query, Integer decoder_code) {
        ResultSet rs = null;
        try {
            if (this.estado) {
                Statement stm = cnx.createStatement();
//                System.out.println("[" + DecoderHelper.getDecoderName(decoder_code) + "][" + query + "]");
                Log.log("[" + DecoderHelper.getDecoderName(decoder_code) + "][" + query + "]", Log.DEBUG);
                rs = stm.executeQuery(query);
            } else {
                //guardar en el log
                writeLog(query);
            }
        } catch (SQLException ep) {
//            Log.log("[VehposDao]Ex: " + ep, Log.ERROR);
//
////            if (ex instanceof org.postgresql.util.PSQLException) {
//            if (ConnectionManager.tryConnection(cnx)) {
//                //El fallo es de la query
//                writeLog(query);
//            } else {
//                if (ConnectionManager.tryConnection()) {
//                    // la conexion esta muerta
//                    resetConection();
//                    execute(query, decoder_code);
//                } else {
//                    // BD muerta
//                    ConnectionManager.reconnect();
//                    cnx = ConnectionManager.getSessionFact();
//                    if (cnx == null) {
//                        ConnectionManager.reconnect();
//                        this.estado = false;
//                        writeLog(query);
//                    } else {
//                        execute(query, decoder_code);
//                    }
//                }
//            }
        }
        return rs;
    }

    public void resetConection() {
//        try {
//            if (cnx == null) {
//                cnx = ConnectionManager.getSessionFact();
//            } else if (cnx.isClosed()) {
//                cnx = ConnectionManager.getSessionFact();
//            } else {
//                cnx.close();
//                cnx = ConnectionManager.getSessionFact();
//            }
//        } catch (SQLException ep) {
//            Log.log("Error reseteando sesion: " + ep, Log.ERROR);
//        }
    }

    private void writeLog(String string) {
//        System.out.println("[VehposDao]Escribiengo en el log: " + string);
//        ConnectionManager.writeLog(string);
    }

    private void replace(StringBuffer buff, String toReplace, String replaceTo) {
        int start;
        while ((start = buff.indexOf(toReplace)) >= 0) {
            buff.replace(start, start + toReplace.length(), replaceTo);
        }
    }

    @Override
    public void CLOSE_SESSION() {
        try {
            cnx.close();
            Log.log("Conexion cerrada");
        } catch (SQLException ep) {
            Log.log("Error cerrando conexion: " + ep, Log.ERROR);
        }
    }

    public boolean getEstado() {
        return this.estado;
    }

}
